package com.wetool.spec.invoicing;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import com.wetool.entity.invoicing.Supplier;
import com.wetool.model.invoicing.SearchParam;

public class SupplierSpec implements Specification<Supplier> {

	private final SearchParam supplier;

	public SupplierSpec(SearchParam supplier) {
		this.supplier = supplier;
	}

	@Override
	public Predicate toPredicate(Root<Supplier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
		// TODO Auto-generated method stub
		List<Predicate> predicates = new ArrayList<>();
		Predicate pred = null;
		predicates.add(cb.and(cb.equal(root.get("isDeleted"), false)));
		if (supplier.getShopId() != null) {//查询对应店铺
			pred = cb.and(cb.equal(root.get("shopId"), supplier.getShopId()));
			predicates.add(pred);
		}
		if (StringUtils.isNotEmpty(supplier.getKey())) {//模糊查询供应商名称
			pred = cb.and(cb.like(root.get("supplierName"), "%" + supplier.getKey() + "%"));
			predicates.add(pred);
		}
		predicates.add(pred);
		return andTogether(predicates, cb);
	}

	private Predicate andTogether(List<Predicate> predicates, CriteriaBuilder cb) {
		return cb.and(predicates.toArray(new Predicate[0]));
	}

}
